var Globals = {
    courses: {},
    modules: {},
    moduleExams: {},
    nextModuleBox: 0,
	view: 'boxes',
	allowdrop: false,
	startYear: 2004,
	endYear: 2009
}

function grade2str(grade) {
    grade = Math.round(grade*10)/10;
    if (Math.round(grade) == grade) grade = grade+'.0';
    if (grade == '0.0') grade = "IP";
    return grade;
}

function dropIntoModule(target) {    
    // This will get a little dirty. We've got to find the element that was
    // Just dropped into this module. Ugh.
    var mid = target.id.replace('mod','');
    var nodes = target.childNodes;
    $A(nodes).each(function(node) {
        if (node.id.startsWith('course')) {
            cid = node.id.replace('course','');
            Globals.courses[cid].module = mid;                        
        }
    });
    Globals.modules[mid].update();
    
}

function dropIntoTimeline(target) {
	slot = Globals.timeline.slots[target.id];
	
//	$("debug").innerHTML += target.id+"<ul>"
	
	var nodes = target.childNodes;

    $A(nodes).each(function(node) {
    	
        if (node.id.startsWith('timelinecourse')) {
            course = Globals.courses[node.id.replace('timelinecourse','')];
//			$("debug").innerHTML += "<li>"+course.name+"</li>";
            course.instance = course.instances[''+slot.year+slot.term];
        }
    });

	slot.update();
//	$("debug").innerHTML += "</ul>"
	
	var nodes = target.childNodes;
	
}				
			
function updateSortables() {    
    moduleBoxes = Array();	

    for (mid in Globals.modules) moduleBoxes.push('mod'+mid);
	for (mid in Globals.modules) {
		Sortable.create('mod'+mid, {tag:'div',dropOnEmpty: true, containment: moduleBoxes, only: 'course', onUpdate: dropIntoModule, constraint: '', hoverclass: 'validdrop', handle: 'handle'});
	}

	for (year in Globals.timeline.slots) {
		Sortable.create(year, {tag:'div',dropOnEmpty: true, containment: Globals.slotArray, only: 'course', onUpdate: dropIntoTimeline, constraint: '', hoverclass: 'validdrop', handle: 'handle'});

	}

}


var Support = {
    
    addCourse: function() {
        if ($F('c_name').length < 4) $('c_name').style.borderColor = "red";
        else {

            Message.hide();
        
            new Ajax.Request('src/addcourse.php', {
                method: 'post',
                parameters: {
                    name: $F("c_name"),
                    credits: $F("c_credits"),
                    area1: $F("c_area1"),
                    external: $F("c_external")
                },
                onSuccess: function(transport){
                    $("debug").innerHTML = transport.responseText;
                    Loader.loadCourse(transport.responseText);
                }
            });
                
        }
    },

    feedback: function() {
        $("feedbackbutton").blindUp()
        new Ajax.Request('src/feedback.php', {
            method: 'post',
            parameters: {mail: $F("feedbackarea")},
            onSuccess: function(transport){
                Message.hide();
            }
        });

    },
    
    autoLogin: function() {
        Globals.loggedIn = true;
        $("menulogout").style.display="inline";
        Support.load();
    },
    
    login: function(callback) {
        $("debug").innerHTML ="logging in";
        new Ajax.Request('src/login.php', {
            method: 'post',
            parameters: {
                username: $F("username"),
                password: $F("password")
            },
            onSuccess: function(transport){
                if (transport.responseText == "username"){
                    Message.warning("Sorry...", "...but there's no such user in the RZ namespace.");
                }
                else if (transport.responseText == "password") {
                    Message.warning("Sorry...", "...but the password doesn't match the username.");
                }
                else {
                    Globals.loggedIn = true;
                    new Effect.BlindDown("menulogout", {scaleX: true, scaleY: false});
                    Message.hide();
                    eval(callback);
                }
            }
        });
    },
    
    logout: function() {
        new Ajax.Request('src/logout.php', {
            onSuccess: function(transport){
                new Effect.BlindUp("menulogout", {scaleX: true, scaleY: false});
                Globals.loggedIn = false;
                if (transport.responseText == "ok")
                    Message.info("Logout complete", "Not a trace of your presence left on the system...");
                else 
                    Message.info("Logout complete", "You haven't been logged in or your session has expired - so technically speaking, your log-out was successful...");
            }
        });
    },
    
    save: function() {
        if (!Globals.loggedIn) Message.login("Support.save()", " to save your data");
        else {
            var courseStr = "";
            var modStr = "";
            // Traverse course instances
            for (courseHash in Globals.courses) {
                courseStr += Globals.courses[courseHash].instance.hash+"|"+Globals.courses[courseHash].grade+"|"+Globals.courses[courseHash].module+"@";
            }
            // Traverse Modules
            for (mod in Globals.modules) {
                module = Globals.modules[mod];
                if (module.moduleExam) {
                    modStr += mod+"|"+module.oralExam+"|"+module.grade+"@";
                }
            }
            
            new Ajax.Request('src/save.php', {
                method: 'post',
                parameters: {
                    courses: courseStr,
                    modules: modStr
                },
                onSuccess: function(transport){
                    if (transport.responseText == "ok"){
                        Message.info("Configuration Saved", "If you click 'load', you will now always come back to this configuration.");
                    }
                    else if (transport.responseText == "login") {
                        Message.login("Support.save()", " to save your data");
                    }
                }
            });
            
        }
    },
    
    load: function() {
        if (!Globals.loggedIn) Message.login("Support.load()", " to load your last configuration");
        else {
            // ok, let's first check whether we got to remove something:
            
            if ($H(Globals.courses).size() > 0) {
                for (key in Globals.courses) {
                    Globals.courses[key].destroy(true);
                }
                Globals.moduleExams = {}
            }
        
            new Ajax.Request('src/load.php', {
                onSuccess: function(transport){
                        //Message.info("Configuration Saved", "If you click 'load', you will now always come back to this configuration.");
                    if (transport.responseText == "login") {
                        Message.login(Support.save, "to save your data");
                    } else {                    
                        courseList = {};
                        examList = {};

                        //$("debug").innerHTML = transport.responseText;

                        eval(transport.responseText);

                        for (key in courseList) {
                            Loader.loadCourse(key, undefined, courseList[key].mod, courseList[key].grade, courseList[key].hash);
                        }

                        for (mod in examList) {
                            Globals.modules[mod].moduleExam = true;
                            Globals.modules[mod].oralExam = examList[mod].oral;
                            Globals.modules[mod].grade = examList[mod].grade;
                            Globals.modules[mod].addExamDiv();
                            Globals.modules[mod].update();
                        }


                    }

                }
            });            
        }
                  
    }
}

var Loader = {
    loadPackage: function(id) {
        if (id==0) {
            Loader.loadCourse("fc71f4085b0e9505a40dee7f5f53f3ec");
            Loader.loadCourse("f140bb3df154cee295007af32cbd3b88");
            Loader.loadCourse("86f796c5b0798d5a1830538c4a67b7b6");
            Loader.loadCourse("53f42afc51d687b199246eadc018fa6e");
            Loader.loadCourse("087cde12c71e5ded0d0fcbce012f86f1");
            Loader.loadCourse("2d7b8362c21f451f148a14a6e35f3307");
            Loader.loadCourse("d54db9329630b09ce90792de0d98aa02");
            
        } else if (id==1) {
            Loader.loadCourse("edee2bf989cedf2eea43f2c735d86463");
            Loader.loadCourse("a60883d17542a9292d5544ebaad65592");
            Loader.loadCourse("040ca3573d4e1638c04a7f0e66843697");
            Loader.loadCourse("edac3f0969842da18441746800becc5e");
            Loader.loadCourse("259dbb31e5da8b779d4282595a4a5181");
        }
    },
    
    loadCourse: function(hash, li, module, grade, instanceHash) {
        if (li) hash = li.id;
        
        if (Globals.courses[hash]) {
            $("course"+hash).highlight();
        } else {
            var newCourse = undefined;
            new Ajax.Request('src/loadCourse.php', {
                method: 'post',
                parameters: {
                    cid: hash
                },
                onSuccess: function(transport){

                    var values = transport.responseText.split("@");
                    var courseValues = values[0].split("|");
                    var instances = {};
                    var instancekey = 0;
                    for (var i = 1; i<values.size(); i++) {
                        if (values[i].length > 1) {
                            instanceValues = values[i].split("|");
                            instance = new Instance(instanceValues[0], hash, instanceValues[1], instanceValues[2], instanceValues[3], instanceValues[4]);                            
                            instances[''+instance.year+instance.term] = instance;
                            if (instanceHash == instanceValues[0]) instancekey = ''+instance.year+instance.term;
                        }
                    }
                    var newCourse = new Course(courseValues[0], courseValues[1], courseValues[2], courseValues[3], courseValues[4], courseValues[5], instances, module, grade, courseValues[6], courseValues[7], instancekey);
                    newCourse.update();
                }
            });
        }
        $("course_input").value = "";

    },
    
    loadModules: function() {

        new Ajax.Request('src/loadModules.php', {
            onSuccess: function(transport){
                var modules = eval(transport.responseText);
                modules.each(function(moduleArray) {
                    var module = new Module(moduleArray[0], moduleArray[1], moduleArray[2], moduleArray[3], moduleArray[4])
                    module.update();
                });
            }
        });
        updateSortables();
    },
    
    init: function() {

        Globals.ac = new Ajax.Autocompleter("course_input", "course_list", "src/autocomplete.php", {
            afterUpdateElement : Loader.loadCourse,
        });
        
        Globals.timeline = new Timeline(Globals.startYear, Globals.endYear);


    }
};
